package cn.tsvtc.shop.stream;

import cn.tsvtc.shop.entity.ResultMessage;
import cn.tsvtc.shop.service.CartService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Athena
 * @date: 2020/11/4 22:31
 * @description:
 */
@Component
@EnableBinding(StreamClient.class)
@Slf4j
public class StreamReceiver {

    private CartService cartService;

    @Autowired
    public StreamReceiver(CartService cartService){
        this.cartService=cartService;
    }


    @StreamListener("cartmerge")
    public void msg(Object msg,
                    @Header(name = AmqpHeaders.CHANNEL) Channel channel,
                    @Header(name = AmqpHeaders.DELIVERY_TAG) Long deliveryTag) throws IOException {
        log.error("接收到消息： " + msg);
        if (msg != null) {
            String message = (String) msg;
            String[] split = message.split(":");
            String cart_token=split[0];
            String login_token=split[1];
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ResultMessage resultMessage = cartService.mergeByMQ(cart_token, login_token);
            log.error("合并购物车结果====>"+resultMessage.getState());
        }

        channel.basicAck(deliveryTag,false);
    }
}
